/**
 * QueryImageListTask.java Create on 2012-8-7     
*      
* Copyright (c) 2012-8-7 by yiming     
*      
* @author <a href="alenzhangym@hotmail.com">Yiming</a>     
* @version 1.0 
 */
package com.yimi.taskmanager;

import android.util.Log;

import com.yimi.common.Message;
import com.yimi.common.MessageType;
import com.yimi.service.BaseImageItem;
import com.yimi.service.FailedQuery;
import com.yimi.service.ImageList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * TODO 功能描述    
 *      
 *  
 *      
 * @author Yiming
 * @version 1.0 
 */
public class QueryImageListTask extends Task {
    private HttpURLConnection conn = null;
    private InputStreamReader input = null;
    private int page;
    private String searchName;
    private boolean close;
    /**
     * @param command
     */
    public QueryImageListTask(int page,String searchName,String command) {
        super(command); 
        this.page = page;
        close = false;
        this.searchName = searchName;
    }

    /* (non-Javadoc)
     * @see java.lang.Runnable#run()
     */
    @Override
    public void run() {
        try {
            Log.e(this.info(), "start to run "+taskCommand );
            conn = (HttpURLConnection) new
                    URL(taskCommand).openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(60000);
            conn.connect();
            if (close)
            {
                conn.disconnect();
                return;
            }
            int k = conn.getResponseCode();
            Log.e(this.info(), " conn.getResponseCode is "+ k);
            if (k != 200) {
                this.addFailedMessage(MessageType.EVENT_QUERYIMAGELISTFAILED, MessageType.TYPE_QUERYMAP_HTTPFAILED, new FailedQuery());                
            } else {
                input = new InputStreamReader(
                        conn.getInputStream());
                if (close)
                {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    conn.disconnect();
                    return;
                } 
                StringBuffer result = new StringBuffer();
                char[] buffers = new char[2048];
                int lenth = input.read(buffers); 
                while(lenth>=0){
                    result.append(buffers, 0, lenth);
                    buffers = new char[2048];
                    lenth =  input.read(buffers); 
                }
                Log.e(this.getClass().getName(), "result is " + result);
                JSONArray array =  new
                        JSONArray(result.toString());
                if (array != null) {
                    Log.e(this.getClass().getName(), "size is " + array.length());
                    ImageList imageList = new ImageList();
                    imageList.setSize(array.length());
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject temp = null;
                        try {
                            temp = (JSONObject) array.get(i);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (temp != null) {
                            BaseImageItem image = new BaseImageItem();  
                            image.setIndex(i);
                            try {
                                image.setPreviewURL(temp.getString("preview_url"));
                            } catch (JSONException e) {
                                image.setPreviewURL("");
                            }
                            try {
                                image.setFileURL(temp.getString("file_url"));
                            } catch (JSONException e) {
                                image.setFileURL("");
                            }
                            imageList.getImageList().add(image);
                        }
                    }
                    imageList.setPage(page);
                    imageList.setSearchName(searchName); 
                    Message message = new Message(MessageType.EVENT_QUERYIMAGELISTSUCCESS);
                    message.setType(page);
                    message.setResult(imageList);
                    addMessage(message);
                } else{
                    addFailedMessage(MessageType.EVENT_QUERYIMAGELISTFAILED, MessageType.TYPE_QUERYMAP_ANALYZE, new FailedQuery());
                }
             }       
        } catch (Exception e) {
                Log.e(this.info(), e.toString());
             addFailedMessage(MessageType.EVENT_QUERYIMAGELISTFAILED, MessageType.TYPE_QUERYMAP_ANALYZE, new FailedQuery());
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }


    }

 

    /* (non-Javadoc)
     * @see com.yimi.taskmanager.Task#info()
     */
    @Override
    public String info() { 
        return "QueryImageListTask";
    }

    /* (non-Javadoc)
     * @see com.yimi.taskmanager.Task#stop()
     */
    @Override
    public void stop() {
        this.listners.removeAllElements();
        close = true;
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

}
